<?php

namespace app\common\service;

use app\common\util\EnvHelper;
use EasyWeChat\OfficialAccount\Application;
use think\facade\Log;
use app\common\model\Config;
use app\common\model\Wxuser;

class WechatOffcialService extends Service
{
    const TEMPLATES = [
        'DEV' => [
            'order_success' => 'a',
            'verify' => 'b',
            'refund' => 'c',
            'refund_result' => 'd'
        ],
        'TEST' => [
            'order_success' => 'a',
            'verify' => 'b',
            'refund' => 'c',
            'refund_result' => 'd'
        ],
        'PROD' => [
            'order_success' => 'a',
            'verify' => 'b',
            'refund' => 'c',
            'refund_result' => 'd'
        ]
    ];

    /**
     * $app 微信公众号实例
     *
     * @var \EasyWeChat\OfficialAccount\Application
     */
    protected $app;

    protected $template;

    public function __construct($app)
    {
        parent::__construct($app);
        $config = Config::getConfigContent('wechat_official');
        if (empty($config)) {
            throw $this->exception('公众号配置为空，无法使用公众号相关功能');
        }
        $wxconfig = [
            'app_id' => $config->app_id,
            'secret' => $config->app_secret,
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'http' => [
                'retry_delay' => 5.0,
                'retry' => [
                    // 发送模板消息可能经常出错，多试几次
                    'max_retries' => 5,
                ]
                // 代理
                // 'proxy' => 'http://qqyun.ycxxkj.com:38092',
            ],
        ];

        $this->app = new Application($wxconfig);

        $releaseType = EnvHelper::getReleaseType();
        $this->template = match ($releaseType) {
            EnvHelper::RELEASE_TYPE_DEV => self::TEMPLATES['DEV'],
            EnvHelper::RELEASE_TYPE_TEST => self::TEMPLATES['TEST'],
            EnvHelper::RELEASE_TYPE_PROD => self::TEMPLATES['PROD'],
            default => self::TEMPLATES['DEV'],
        };
    }


    /**
     * 发送微信消息
     *
     * @param Wxuser $user 用户
     * @param string $templateId 模板id
     * @param array $data 模板数据
     * @param string $path 跳转路径
     *
     * @return void
     */
    public function sendWechatMessage($user, string $templateId, array $data, string $path = '/pages/home/home')
    {
        if (!$user?->mp_openid) {
            Log::info("用户{$user->id}没有mp_openid, 已忽略");
            return;
        }

        $openid = $user->mp_openid;
        try {
            $response = $this->app->getClient()->post('/cgi-bin/message/template/send', [
                'json' => [
                    'touser' => $openid,
                    'template_id' => $templateId,
                    'data' => $data
                ]
            ]);
            $body = $response->toArray(true);
            if ($body['errcode'] == 0) {
                // 标记为成功发送
                Log::info("发送微信公众号模板消息给用户 openid=$openid 成功");
            } else {
                Log::error("发送微信公众号模板消息给用户 openid=$openid 失败[{$body['errcode']}]：{$body['errmsg']}");
            }
        } catch (\Exception $e) {
            Log::warning("发送微信公众号模板消息给用户 openid=$openid 失败[{$e->getCode()}]：{$e->getMessage()}");
        }
    }

    public function sendOrderSuccessMessage()
    {
        $templateId = $this->template['order_success'];
    }

    public function sendVerifyMessage()
    {
        $templateId = $this->template['verify'];
    }

    public function sendRefundMessage()
    {
        $templateId = $this->template['refund'];
    }

    public function sendRefundResultMessage()
    {
        $templateId = $this->template['refund_result'];
    }
}